<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------

namespace api\v1\controller;

use api\v1\model\Advertise;
use api\v1\model\Article;
use api\v1\model\Auth;
use api\v1\model\Bank;
use api\v1\model\Category;
use api\v1\model\Level;
use api\v1\model\Lottery;
use api\v1\model\Moneylog;
use api\v1\model\Order;
use api\v1\model\Prize;
use api\v1\model\Product;
use api\v1\model\Recharge;
use api\v1\model\Signlog;
use api\v1\model\User;
use api\v1\model\Withdraw;
use cmf\controller\RestBaseController;
use cmf\controller\RestUserBaseController;
use think\facade\Db;

/**
 * 首页接口
 * Class IndexController
 * @package api\v1\controller
 */
class UserController extends RestUserBaseController
{
    public function userInfo()
    {
        $user = User::with(['level', 'auth', 'bank'])->find($this->userId);
        $user->chicang = Order::where("user_id",$user->id)
            ->where("status",1)
            ->sum("amount");
        $user->yeb_yestoday_shouyi = 0;
        $yeb_shouyi = Moneylog::where("user_id",$user->id)
            ->where("type",9)
            ->whereTime("create_time",'>',strtotime('today')-60*60)->find();
        if($yeb_shouyi) {
            $user->yeb_yestoday_shouyi = $yeb_shouyi->money;
        }
        $this->success("ok", ['user' => $user]);
    }

    public function order_list() {

        $list = Order::with("product")->where("user_id",$this->userId)
            ->order("id",'desc')
            ->paginate();
        $this->success("ok",['list'=>$list->items(),'total'=>$list->total()]);
    }

    public function update() {
        $res = User::where("id",$this->userId)->update($this->request->post());
        if($res) {
            $this->success("更新成功！");
        }
        $this->error("更新失败！");

    }
    //签到
    public function sign()
    {
        $today = strtotime("today");
        $yestoday = $today - (60 * 60 * 24);
        $last = Signlog::where('user_id', $this->user->id)->order('id', 'desc')->find();
        $last_create_time = $last ? $last->create_time : 0;
        if ($last_create_time > $today) {
            $this->error("今日已签！");
        }
        $num = 1;
        if ($last_create_time > $yestoday) {
            $num = $num + $last->lianxu_num;
        }
        $log = Signlog::create([
            'user_id' => $this->user->id,
            'lianxu_num' => $num
        ]);
        $this->success("签到成功！", $log);
    }

    public function levels()
    {
        $this->success("ok", Level::order("id", 'asc')->select());
    }

    public function team()
    {
        $level = $this->request->param("level");
        $uids = User::team_member_uids($this->userId, $level);
        $members = User::withSum('orders', 'amount')
            ->with("level")
            ->whereIn("id", $uids)
            ->order("id", "desc")
            ->select();
        $this->success("ok", ['members' => $members]);
    }

    public function auth()
    {
        $auth = Auth::where("user_id", $this->userId)->find();
        $post = $this->request->post();
        if (empty($auth)) {
            $auth = new Auth();
        }
        if ($auth->status != 1) {
            $auth->status = 0;
            $auth->user_id = $this->userId;
            $auth->realname = $post['realname'];
            $auth->idcard = $post['idcard'];
            $auth->img_back = $post['img_back'];
            $auth->img_front = $post['img_front'];
            $auth->save();
            $this->success("信息已提交，请等待审核！");
        }
        $this->error("已实名，不能重复认证！");
    }

    public function bank()
    {
        $bank = Bank::where("user_id", $this->userId)->find();
        $post = $this->request->post();
        if (empty($bank)) {
            $bank = new Bank();
        }
        $bank->user_id = $this->userId;
        $bank->card_user_name = $post['card_user_name'];
        $bank->bank_name = $post['bank_name'];
        $bank->bank_no = $post['bank_no'];
        $bank->card_phone = $post['card_phone'];
        $bank->save();
        $this->success("操作成功");
    }

    public function resetPass()
    {
        $pass = $this->request->param("newpass");
        $oldpass = $this->request->param("oldpass");
        $user = User::find($this->userId);
        if (!cmf_compare_password($oldpass, $user->user_pass)) {
            $this->error("旧密码输入错误！");
        }
        $user->user_pass = cmf_password($pass);
        $user->save();
        $this->success("操作成功！");
    }

    public function resetPayPass()
    {
        $pass = $this->request->param("newpass");
        $oldpass = $this->request->param("oldpass");
        $user = User::find($this->userId);
        if ($user->pay_pass&&!cmf_compare_password($oldpass, $user->pay_pass)) {
            $this->error("旧密码输入错误！");
        }
        $user->pay_pass = cmf_password($pass);
        $user->save();
        $this->success("操作成功！");
    }
    public function withdraw() {
        $num = floatval($this->request->param('num'));
        $user = User::with("bank")->find($this->userId);
        if($user->balance<$num) {
            $this->error("余额不足！");
        }
        Db::startTrans();
        try {
            Withdraw::create([
                "user_id"=>$this->userId,
                "card_user_name"=>$user->bank->card_user_name,
                "bank_name"=>$user->bank->bank_name,
                "bank_no"=>$user->bank->bank_no,
                "card_phone"=>$user->bank->card_phone,
                "amount"=>$num
            ]);
            $user->balance = $user->balance - $num;
            $user->save();
            Db::commit();
        }
        catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("操作成功,请等待审核！");
    }
    public function recharge()
    {
        $num = floatval($this->request->param('num'));
        if ($num > 0) {
            Recharge::create([
                "user_id" => $this->userId,
                "amount" => $num
            ]);
            $this->success("操作成功，请等待审核！");
        }
    }
    public function moneylog() {
        $type = $this->request->param("type");
        $query = Moneylog::where("user_id",$this->userId);
        if($type) {
            $query->where("type",$type);
        }
        $list = $query->order('id','desc')
            ->paginate();
        $this->success("ok",['list'=>$list->items(),'total'=>$list->total()]);
    }
    public function withdrawlog() {
        $list = Withdraw::where("user_id",$this->userId)->order('id','desc')
            ->paginate();
        $this->success("ok",['list'=>$list->items(),'total'=>$list->total()]);
    }
    public function rechargelog() {
        $list = Recharge::where("user_id",$this->userId)
            ->order('id','desc')
            ->paginate();
        $this->success("ok",['list'=>$list->items(),'total'=>$list->total()]);
    }
    public function yebAdd() {
        $num = floatval($this->request->param("num"));
        if($num <= 0) {
            $this->error("请输入正确的金额");
        }
        Db::startTrans();
        try {
            $user = User::lock(true)->find($this->userId);
            if ($user->balance < $num) {
                $num = $user->balance;
            }
            $user->balance = $user->balance - $num;
            $user->yeb = $user->yeb + $num;
            $user->yeb_add_time = strtotime("today");
            $user->save();
            Db::commit();
        }
        catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("操作成功！");
    }
    public function yebSub() {
        $num = floatval($this->request->param("num"));
        if($num <= 0) {
            $this->error("请输入正确的金额");
        }
        Db::startTrans();
        try {
            $user = User::lock(true)->find($this->userId);
            if ($user->yeb < $num) {
                $num = $user->yeb;
            }
            $user->balance = $user->balance + $num;
            $user->yeb = $user->yeb - $num;
            if($user->yeb_enabled < $num) {
                $user->yeb_enabled = 0;
            }
            else {
                $user->yeb_enabled = $user->yeb_enabled - $num;
            }
            //$user->yeb_add_time = strtotime("today");
            $user->save();
            Db::commit();
        }
        catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("操作成功！");
    }
    public function lotteryconfig() {
        $list = Lottery::field("id as prizeId,name as prizeName,img as prizeImage")->select();
        foreach($list as $l) {
            $l->prizeImage = cmf_get_image_url($l->prizeImage);
        }
        $this->success("ok",$list);
    }
    public function getprizeid() {

        $list = Lottery::field("id,name,prize,img,winningrate as rate")
            ->order("winningrate","asc")
            ->select();
        $total = 0;
        $rates = [];
        foreach ($list as $item) {
            $total += $item->rate;
            $rates[] = $total;
        }
        $lucky = mt_rand(0,$total);
        foreach($rates as $k=>$v) {
            if($lucky<=$v) {
                $gift = $list[$k];
                break;
            }
        }
        if($gift->title != "谢谢参与") {
            $prize = new Prize();
            $prize->lottery_id = $gift->id;
            $prize->name = $gift->name;
            $prize->img = $gift->img;
            $prize->prize = $gift->prize;
            $prize->user_id = $this->userId;
            $prize->save();
        }
        $this->success("ok",$gift->id);
    }
    public function prizeList() {
        $list = Prize::with("lottery")->where('user_id',$this->userId)->paginate();
        $this->success("ok",['list'=>$list->items(),'total'=>$list->total()]);
    }
}
